import Vue from 'vue'
import Router from 'vue-router'
import Login from './components/Login.vue'
// 配置首页的路由
import Home from './components/Home.vue'
import Welcome from './components/Welcome.vue'
import Users from './components/users/Users.vue'
import Rights from './components/power/Rights.vue'
import Roles from './components/power/Roles.vue'
import Cate from './components/goods/Cate.vue'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      // 子路由，默认进入此页面
      children: [
        {
          path: '/welcome',
          component: Welcome
        },
        {
          path: '/users',
          component: Users
        },
        {
          path: '/rights',
          component: Rights
        },
        {
          path: '/roles',
          component: Roles
        },
        {
          path: '/categories',
          component: Cate
        }
      ]
    }
  ]
})

// 挂载路由守卫，判断是否有token
router.beforeEach((to, from, next) => {
  // 如果是登录界面，放行
  // to 代表要访问的路径
  // from 代表来源路径
  // next 代表放行路径
  if (to.path === '/login') return next()
  // 判断是否有token
  const token = window.sessionStorage.getItem('token')
  if (!token) return next('/login')
  // 都符合，则放行
  next()
})

// 暴露路由
export default router
